package com.mmall.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.Exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

public class BeanVaildator {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * 单个类的校验工具
     * @param t 校验对象
     * @param groups 校验组
     * @param <T>
     * @return
     */
    public static <T> Map<String,String> validate(T t,Class... groups){
        //拿到验证对象信息
        Validator validator = validatorFactory.getValidator();
        //对被校验的进行验证
        Set validateResult = validator.validate(t,groups);
        if (validateResult.isEmpty()){
            //如果校验后没有问题就返回空
            return Collections.emptyMap();
        }else{
            //实例化的MAP类
            LinkedHashMap errors = Maps.newLinkedHashMap();
            //对错误信息开始遍历
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()){
                //将校验信息实例到ConstraintViolation对象中
                ConstraintViolation violation = (ConstraintViolation)iterator.next();
                //获取key，和value存放到map中
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return  errors;
        }
    }

    /**
     * list类型的校验工具
     * @param collection list对象
     * @param <T>
     * @return
     */
    public static Map<String,String> validateList(Collection<?> collection){
        //判断对象是否为空，如果为空返回空指针异常
        Preconditions.checkNotNull(collection);
        //遍历数据
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if (!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validate(object,new Class[0]);
        }while (errors.isEmpty());
        return errors;
    }

    /**
     * 多对象同时校验的校验工具
     * @param first
     * @param objects
     * @return
     */
    public static Map<String,String> validateObject(Object first,Object... objects){
        if (objects != null && objects.length>0){
           return validateList(Lists.asList(first,objects));
        }else {
           return validate(first,new Class[0]);
        }
    }

    /**
     * 检查
     * @param param
     */
    public static  void check(Object param){
        Map errors = validateObject(param);
        if (MapUtils.isNotEmpty(errors)){
            throw new ParamException(errors.toString());
        }
    }
}
